package com.xuecheng.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author 勾新杰
 * @version 1.0
 * @description 安全管理配置
 * @date 2022/9/26 20:53
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) // 启用基于方法的安全性，允许使用 @Secured 和 @PreAuthorize/@PostAuthorize 注解进行细粒度的方法级别的权限控制。
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private DaoAuthenticationProviderCustom daoAuthenticationProviderCustom;

    /**
     * 注入自定义认证方式
     * @param daoAuthenticationProviderCustom 自定义认证方式
     */
    @Autowired
    public void setDaoAuthenticationProviderCustom(DaoAuthenticationProviderCustom daoAuthenticationProviderCustom) {
        this.daoAuthenticationProviderCustom = daoAuthenticationProviderCustom;
    }

    /**
     * 框架对比密码时使用的加密方式，将传入的密码进行加密再和数据库对比matches，这种加密方式不能反向解密
     * @return 密码加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
       return new BCryptPasswordEncoder();
    }

    /**
     * 配置自定义认证方式，原来的认证方式是对比密码，现在直接放行就好，在这之前进行不同种的认证实现
     * @param auth 认证管理对象
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(daoAuthenticationProviderCustom);
    }

    // 配置安全拦截机制
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/r/**").authenticated()// 访问/r开始的请求需要认证通过
                .anyRequest().permitAll()// 其它请求全部放行
                .and()
                .formLogin().successForwardUrl("/login-success");// 登录成功跳转到/login-success
    }

    /**
     * 认证管理对象
     * @return 认证管理对象
     * @throws Exception 异常
     */
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    public static void main(String[] args) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println(passwordEncoder.encode("123456"));
    }
}
